import Scanner from './Scanner'

export default function (templateStr) {
  let scanner = new Scanner(templateStr)
  let words
  let tokens = []
  while (!scanner.eos()) {
    words = scanner.scanUntil('{{')
    if (words) {
      tokens.push(['text', words.replace(/\s{2,}/g, ' ')])
    }
    scanner.scan('{{')
    words = scanner.scanUntil('}}')
    if (words) {
      if (words[0] == '#') {
        tokens.push(['#', words.substring(1)])
      } else if (words[0] == '/') {
        tokens.push(['/', words.substring(1)])
      } else {
        tokens.push(['name', words])
      }
    }
    scanner.scan('}}')
  }
  return nestedTokens(tokens)
}
function nestedTokens(tokens) {
  let res = []
  let collector = res
  let section = []
  for (let i = 0; i < tokens.length; i++) {
    let token = tokens[i]
    switch (token[0]) {
      case '#':
        collector.push(token)
        collector = token[2] = []
        section.push(token)
        break;
      case '/':
        section.pop()
        collector = section.length == 0 ? res : section[section.length - 1][2]
        break;
      default:
        collector.push(token)
    }
  }
  return res
}